package com.aote.expression.paramprocessor;

import java.util.Iterator;
import java.util.Map;

import org.w3c.dom.Element;

import com.aote.expression.Param;
import com.browsesoft.PropertiesService;
import com.browsesoft.dbtools.DBTools;
import com.browsesoft.htmlcomponent.HTMLBasicComponent;
import com.browsesoft.user.User;

public class SqlProcessor implements ParamProcessor {

	public String process(Param param, Map attribures, User loginUser,
			HTMLBasicComponent component) {
		try {
			String name = (String) param.getParams().get("name");
			// 根据名称从属性文件
			Element sqlElem = (Element) PropertiesService.getDocument()
					.getElementsByTagName(name).item(0);
			String sql = sqlElem.getAttribute("sql");
			if(param.getParams().containsKey("params"))
			{
				String p = param.getParams().get("params").toString();
				if(p.equals("loginuser"))
				{
					Iterator iter = loginUser.getAttributes().keySet().iterator();
					while (iter.hasNext()) {
						String key = (String) iter.next();
						String value = (String) loginUser.getAttributes().get(key);
						sql = sql.replaceAll("#" + key + "#", value);
					}
				}
			}
			Iterator iter = attribures.keySet().iterator();
			while (iter.hasNext()) {
				String key = (String) iter.next();
				String value = (String) attribures.get(key);
				sql = sql.replaceAll("#" + key + "#", value);
			}
			String[][] datas = DBTools.executeQueryWithTableHead(sql);
			if (datas.length > 1) {
				return datas[1][0];
			} else {
				return "";
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
